package top.wshape1.shiziapi.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import top.wshape1.shiziapi.common.constant.BizCodeEnum;

import java.io.Serializable;

/**
 * @author Wshape1
 * @version 1.0
 * @description
 * @since 2023-08-13
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class R<T> implements Serializable {

    private Integer code;

    private String msg;

    private T data;

    public <t> t getData(Class<t> clazz) {
        return JSON.parseObject((String) data, clazz);
    }

    public <t> t getData(TypeReference<t> typeReference) {
        return JSON.parseObject((String) data, typeReference);
    }

    public <t> R<t> putData(t data) {
        R<t> r = new R<>(this.getCode(), this.getMsg());
        r.setData(data);
        return r;
    }

    public R(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static <T> R<T> ok() {
        return new R<>(0, "success");
    }

    public static <T> R<T> ok(String msg) {
        return new R<>(0, msg);
    }

    public static <T> R<T> ok(T data) {
        R<T> r = new R<>(0, "success");
        r.setData(data);
        return r;
    }

    public static <T> R<T> error() {
        return new R<>(BizCodeEnum.UNKNOWN_ERROR.code(), BizCodeEnum.UNKNOWN_ERROR.msg());
    }

    public static <T> R<T> error(String msg) {
        return new R<>(BizCodeEnum.UNKNOWN_ERROR.code(), msg);
    }

    public static <T> R<T> instance(Integer code, String msg) {
        return new R<>(code, msg);
    }

    public static <T> R<T> instance(BizCodeEnum bizCodeEnum) {
        return new R<>(bizCodeEnum.code(), bizCodeEnum.msg());
    }

    @JsonIgnore
    public boolean isSuccessful() {
        return code == 0;
    }


}
